package com.wiiss.ams.cron.task.action.action_holder;


import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.cronutils.utils.StringUtils;
import com.wiiss.ams.cron.task.action.collecting_handling_cron_action.CollectingAndHandlingCronAction;
import com.wiiss.ams.dao.MysqlDML;
import com.wiiss.ams.util.DateUtils;
import com.wiiss.ams.util.Exc;
import com.wiiss.ams.util.http.HttpRequest;
import com.wiiss.ams.util.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

import static cn.hutool.http.Header.*;
import static cn.hutool.http.Method.POST;

public class Hb04ActionHolder {
    private static final Logger log = LoggerFactory.getLogger(Hb04ActionHolder.class);

    public static final CollectingAndHandlingCronAction DEVICE_ALARM = createAction_BI_DEVICE_ALARM();


    private static CollectingAndHandlingCronAction createAction_BI_DEVICE_ALARM() {
        return new CollectingAndHandlingCronAction("设备报警", cron -> {

            String startSql = """
                    SELECT
                        a.id,
                        a.alarm_code ALM_ID,
                        a.alarm_reson ALARM_NAME,
                            CASE
                             WHEN a.alarm_level = '1' THEN 'P'
                                     WHEN a.alarm_level = '2' THEN 'K'
                                     WHEN a.alarm_level = '3' THEN 'G'
                             ELSE null
                         END ALM_LEVEL,
                        a.alarm_time STARTTIME,
                            CASE
                             WHEN a.alarm_action = 1 THEN 'False'
                             ELSE 'True'
                         END FLAG,
                            a.equipment_code EQU_ID,
                            a.equipment_name EQU_NAME,
                            a.workshop_name BU,
                            a.equipment_type EQU_TYPE,
                            CASE
                             WHEN a.task_code is null	THEN '1'
                                     WHEN a.task_code = ''	THEN '1'
                             ELSE '0'
                         END IS_RUN,
                            a.equipment_type SYSTEM_NAME,
                        a.alarm_time_end ENDTIME,
                        a.remark
                    FROM
                        mcs_equipment_alarm_up a 
                    WHERE a.alarm_action = 0
                      AND a.alarm_time >= NOW() - INTERVAL 3 DAY;
                    """;
            List<JSONObject> hb04StartAlarmList = MysqlDML.get("hb04.mcs", startSql, LocalDateTime.now(), LocalDateTime.now());
            if (CollectionUtils.isEmpty(hb04StartAlarmList)) {
                log.info("无发生告警信息");
            }
            List<String> hb04StartIds = hb04StartAlarmList.stream().map(it -> it.getStr("id")).toList();
            log.info("发生未解除的报警ID有{}", hb04StartIds);
            sendAms(hb04StartAlarmList);

            String endSql = """
                    SELECT
                        a.id,
                        a.alarm_code ALM_ID,
                        a.alarm_reson ALARM_NAME,
                        CASE
                         WHEN a.alarm_level = '1' THEN 'P'
                                 WHEN a.alarm_level = '2' THEN 'K'
                                 WHEN a.alarm_level = '3' THEN 'G'
                         ELSE null
                        END ALM_LEVEL,
                        a.alarm_time STARTTIME,
                         CASE
                             WHEN a.alarm_action = 1 THEN 'False'
                             ELSE 'True'
                         END FLAG,
                        a.equipment_code EQU_ID,
                        a.equipment_name EQU_NAME,
                        a.workshop_name BU,
                        a.equipment_type EQU_TYPE,
                         CASE
                             WHEN a.task_code is null	THEN '1'
                                     WHEN a.task_code = ''	THEN '1'
                             ELSE '0'
                         END IS_RUN,
                        a.equipment_type SYSTEM_NAME,
                        a.alarm_time_end ENDTIME,
                        a.remark
                    FROM
                        mcs_equipment_alarm_up a 
                    WHERE a.remark IS NULL
                        AND a.alarm_action = 1;
                    """;
            List<JSONObject> hb04EndAlarmList = MysqlDML.get("hb04.mcs", endSql, LocalDateTime.now(), LocalDateTime.now());
            if (CollectionUtils.isEmpty(hb04EndAlarmList)) {
                log.info("无解除告警信息");
                return new ArrayList<>();
            }
            List<String> hb04EndIds = hb04EndAlarmList.stream().map(it -> it.getStr("id")).toList();
            log.info("已解除的报警ID有{}", hb04EndIds);

            List<JSONObject> updateRemarkList = hb04EndAlarmList.stream().map(it -> {
                JSONObject remark = new JSONObject();
                remark.set("remark", 0);
                remark.set("id", it.get("id"));
                return remark;
            }).toList();

            Integer i = MysqlDML.batchUpdate("hb04.mcs", "mcs_equipment_alarm_up", updateRemarkList);
            log.info("成功更新转状态为0数量{}", i);
            sendAms(hb04EndAlarmList);
            return updateRemarkList;
        }, ((cron, dataList) -> {
            if (CollectionUtils.isEmpty(dataList)) return "effect rows num " + 0;
            Integer count;

            List<JSONObject> updateRemarkList1 = dataList.stream().map(it -> {
                JSONObject remark1 = new JSONObject();
                remark1.set("remark", 1);
                remark1.set("id", it.getStr("id"));
                return remark1;
            }).toList();

            count = MysqlDML.batchUpdate("hb04.mcs", "mcs_equipment_alarm_up", updateRemarkList1);
            log.info("成功更新在状态为1数量{}", count);

            return "effect rows num " + count;
        }));
    }

    private static void sendAms(List<JSONObject> hb04AlarmList) {
        JSONObject obj = JSONUtil.createObj(JSONConfig.create().setIgnoreNullValue(false));
        obj.set("From", "AMS_JOB");
        obj.set("Message", "WebAPI_KAlarmMsg");
        hb04AlarmList.forEach(it -> {
            it.remove("id");
            it.remove("remark");
            it.set("LOGDATE", "");
            it.set("PRC", "");
            it.set("IS_DEL", "0");
            it.set("SEND_TYPE", "0");
            it.set("IS_SEND", "0");
            it.set("MSG_GROUP", "");
            it.set("GUID", "");
            it.set("BUMEN", "");
            it.set("KEBIE", "");
            try {
                it.set("STARTTIME", DateUtils.parseStrToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, it.getStr("STARTTIME")));
            } catch (Exception e) {
                log.error("STARTTIME error", e);
            }
            try {
                it.set("ENDTIME", "True".equals(it.getStr("FLAG")) ? "" : DateUtils.parseStrToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, it.getStr("ENDTIME")));
            } catch (Exception e) {
                log.error("ENDTIME error", e);
            }
            obj.set("Content", JSONUtil.toJsonStr(it));
            obj.set("DateTime", DateUtils.getStandardTime(new Date()));
            HttpRequest httpRequest = new HttpRequest(POST,
                    "http://10.90.65.72:5804/api/WebAPI_KAlarmMsg/WebAPI_KAlarmMsg",
                    new HashMap<>(Map.of(CONNECTION.getValue(), "keep-alive", CONTENT_TYPE.getValue(), "application/json;charset=UTF-8")),
                    obj);
            log.info("请求参数为{}", JSONUtil.toJsonStr(obj));
            HttpResponse response = HttpUtil.request(httpRequest);
            log.info("返回参数为{}", JSONUtil.toJsonStr(response));
            if (response == null || response.getStatus() != 200 || StringUtils.isEmpty(response.body())) {
                throw new Exc("调用ams服务异常");
            }
            log.info("返回参数为{}", JSONUtil.toJsonStr(response.body()));
            String code = JSONUtil.parseObj(response.body()).getStr("Code");
            if (!"0000".equals(code)) {
                throw new Exc("调用ams上报接口返回异常");
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                log.error("sleep error", e);
            }
        });
    }
}
